package ScoreBoard.Login.Model;

import java.net.*;
import java.io.*;

import Exception.SocketConnectionFailureException;

public class InitializeSocket 
{
    public InitializeSocket(ScoreBoardLoginModel model)
    {
    	this.model = model;
    	initializeServerIp();
    }
    
    public void initializeServerIp()
    {
    	try
		{
		    BufferedReader in = new BufferedReader(new FileReader(this.serverProcessAddressFilePath));
		    serverIp = in.readLine();
		    port = new Integer(in.readLine());
		}
		catch(FileNotFoundException exception)
		{
			System.out.println("FileNotFound : " + this.serverProcessAddressFilePath);
			exception.printStackTrace();
		}
		catch(IOException exception)
		{
		    System.out.println("IOException when read file : " + this.serverProcessAddressFilePath);	
		    exception.printStackTrace();
		}
		catch(Exception exception)
		{
		    System.out.println("Exception happened when initializeServerIp");
		    exception.printStackTrace();
		}
    }
    
    public boolean initializeSocket() throws SocketConnectionFailureException
    {
      	try
      	{
      		this.model.socket = new Socket(serverIp, port);
      		System.out.println("team socket has been created!");
      	}
      	catch(IOException exception)
      	{
      		System.out.println("IOException happened when initialize the Socket!");
      		exception.printStackTrace();
      		throw new SocketConnectionFailureException("Cann't connect to server, Please contact the staff!");
      	}
      	return true;
    }
    
    private ScoreBoardLoginModel model;
    private String serverIp;
    private int port;
    private String serverProcessAddressFilePath = new String("c:\\server_process_address.txt");
}
